import {reroute} from "./reroute";

export const routingEventsListeningTo = ['hashchange', 'popstate'];

function urlReroute(){
  reroute([], arguments);
}

/** 1. 自己先填一点逻辑 */
window.addEventListener('hashchange', urlReroute)
window.addEventListener('popstate', urlReroute)

// 用户可能还会绑定自己的路由事件: vue react
// So 当我们应用切换后, 还需要处理原来的方法, 需要在应用切换后再执行

const originalAddEventListener = window.addEventListener;
const originalRemoveEventListener = window.removeEventListener;

/** 2. 后续针对hashchange和popstate的都拦截掉 */
const captureEventListeners = {
  hashChange: [],
  popstate: []
}
//↑ 当应用切换完成后调用

window.addEventListener = function (eventName, fn) {
  if (
    routingEventsListeningTo.indexOf(eventName) !== -1
    && !captureEventListeners[eventName].some(l => l === fn)
  ) {
    captureEventListeners[eventName].push(fn);
    return;
  }

  return originalAddEventListener.apply(this, arguments);
};

window.removeEventListener = function(eventName,fn){
  if(routingEventsListeningTo.indexOf(eventName) !== -1){
    captureEventListeners[eventName] = captureEventListeners[eventName].filter(l => l !== fn);
    return;
  }
  return originalRemoveEventListener.apply(this, arguments);
}

window.history.pushState = patchedUpdateState(window.history.pushState,'pushState')
window.history.replaceState = patchedUpdateState(window.history.replaceState,'replaceState')

function patchedUpdateState(updateState,methodName){
  return function () {
    const urlBefore = window.location.href;
    updateState.apply(this, arguments); //调用切换方法
    const urlAfter = window.location.href;

    if(urlBefore !== urlAfter){ //之前路径和最新的不一样 就需要重新加载
      urlReroute(new PopStateEvent('popstate'));
    }
  };
}
